package com.cxyd.modules.api.controller;

import com.cxyd.common.annotation.LogApiOperation;
import com.cxyd.common.utils.ApiResult;
import com.cxyd.modules.api.dto.RcsResultHK;
import com.cxyd.modules.wcs.dto.AgvCallbackHkDTO;
import com.cxyd.modules.wcs.dto.ReceiveTaskDTO;
import com.cxyd.modules.wcs.service.AgvCallbackHkService;
import com.cxyd.modules.wcs.service.AgvTrkHkService;
import com.cxyd.modules.wcs.service.ReceiveTaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalTime;

@Slf4j
@RestController
@RequestMapping("/api")
public class ApiController {
    @Resource
    private ReceiveTaskService receiveTaskService;
    @Resource
    private AgvCallbackHkService hkService;

    @Resource
    private AgvTrkHkService agvTrkHkService;

    @GetMapping("ping")
    public ApiResult ping() {
        return new ApiResult().success("当前时间:" + LocalTime.now());
    }

    @PostMapping("receive")
    @LogApiOperation("接收上位任务")
    public ApiResult receiveTask(@RequestBody ReceiveTaskDTO dto) {
        try {
            //1.校验数据格式
            if (dto == null) {
                return new ApiResult().feedBack("无效的请求数据!", "404");
            }
            final String requestPk = dto.getRequestPk();
            final String contNo = dto.getContNo();
            if (requestPk.isEmpty() || contNo.isEmpty()) {
                return new ApiResult().feedBack("[请求ID]或[料箱码]不能为空!", "500");
            }
            //2.校验业务数据
            final ReceiveTaskDTO receiveTask = receiveTaskService.getReceiveTaskByContNo(contNo);
            if (receiveTask != null) {
//                1.任务存在需要判断是否为更新优先级
                boolean flag = receiveTaskService.updateReceiveTaskByPrty(dto, receiveTask);
                if (flag) {
                    return new ApiResult().feedBack(requestPk);
                } else {
                    return new ApiResult().feedBack("料箱[" + contNo + "]任务已存在!", requestPk);
                }
            }
            //3.将数据保存到[wcs_receive_task]表中
            receiveTaskService.save(dto);
            //4.反馈成功
            return new ApiResult().feedBack(requestPk);
        } catch (Exception ex) {
            assert dto != null;
            return new ApiResult().feedBack(ex.getMessage(), dto.getRequestPk());
        }
    }

    @PostMapping("agvCallback")
    @LogApiOperation("HK任务执行通知")
    public RcsResultHK agvCallbackHK(@RequestBody AgvCallbackHkDTO dto) {
        try {
            if (ObjectUtils.isNotEmpty(agvTrkHkService.getAgvTrkByTaskCode(dto.getTaskCode()))) {
                hkService.save(dto);
            }
//            调用callbackHandle处理业务
            return hkService.callbackHandle(dto);
        } catch (Exception ex) {
            log.error("HK任务执行通知失败：" + ex.getMessage());
            return new RcsResultHK().error(dto.getReqCode(), ex.getMessage());
        }
    }
}
